package com.jflm.service.impl;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jflm.common.Element;
import com.jflm.domain.Constant;
import com.jflm.domain.Iresp_common;
import com.jflm.service.IMemberService;
import com.jflm.service.IPropertyService;
import com.jflm.util.ContantRC;
import com.jflm.util.DateUtil;
import com.jflm.util.HttpUtils;
import com.jflm.util.ParamsHelper;
import com.jflm.util.ReqUtils;
import com.jflm.util.StringUtil;

@Service("memberService")
public class MemberServiceImpl implements IMemberService {

	private static final Logger LOG = LoggerFactory.getLogger(MemberServiceImpl.class);

	@Autowired
	private Gson gson;
	@Autowired
	private IPropertyService propertyService;

	@Async
	public Iresp_common addPoints(Map<String, String> map) {
		// 调用收银台接口
		String qrpid = ReqUtils.getRpid("R");
		Date cdate = DateUtil.getCurrentDate();
		map.put(Element.FUNCODE, Constant.FUNCODE_CUMULATIVE);
		map.put(Element.RPID, qrpid);
		map.put(Element.REQDATE, DateUtil.date8(cdate));
		map.put(Element.REQTIME, DateUtil.time6(cdate));
		map.put(Element.CLIENTIP, "127.0.0.1");
		map.put(Element.MERPRIV, "cumulative");
		map.put(Element.EXPAND, "cumulative");
		
		String md5Key = propertyService.getStrValue(map.get(Element.MERID)+".signkey", "123456");
		String respSign = ParamsHelper.makeSign(map, md5Key); // 平台生成商户签名
		map.put(Element.SIGN, respSign);

		LOG.info("请求参数map:{}, 收银台积分加分接口", map);
		String domain = propertyService.getStrValue(Constant.CASHIER_SERVICE_DOMAIN, "");
		String url = domain + "/api/cashier/points/cumulative";
		LOG.info("访问的链接地址:{}", url);
		String bady = gson.toJson(map);
		String fromdata = HttpUtils.doPost(url, bady, null, 3, 10, Constant.CHARSET_UTF_8);
		if (StringUtil.isBlank(fromdata)) {
			return ContantRC.getRetMsg(ContantRC.REVERSE_BINDING_ERROR);
		}
		// 数据转换为map
		Map<String, String> pointscoreMap = gson.fromJson(fromdata, new TypeToken<Map<String, String>>(){}.getType());
		LOG.info("收银台积分加分接口返回信息:{}", pointscoreMap);
		return new Iresp_common(pointscoreMap.get("retCode"), pointscoreMap.get("retMsg"));
	}

	
}
